// var API_BASE_URL = 'https://oa.sinkr.cn/'; //测试环境
// var API_BASE_URL = 'http://localhost:8080/hongpeifrcj86s2/'; //本地环境-PC端后台地址
// var API_BASE_APP_URL = 'http://localhost:8080/hongpeid3f8z2q5/'; //本地环境-移动端后台地址
var API_BASE_URL = 'https://www.lycmcc.com/hongpeifrcj86s2/'; //生产环境-PC端后台地址
var API_BASE_APP_URL = 'https://www.lycmcc.com/hongpeid3f8z2q5/'; //生产环境-移动端后台地址
const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}

/**
* 生成uuid
*/
function generateUUID() {
 return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
     var r = Math.random() * 16 | 0,
         v = c === 'x' ? r : (r & 0x3 | 0x8);
     return v.toString(16);
 });
}


function request(url, data = {}, method = "GET", contentType = "application/json", isLoading = false) {
  url = url.startsWith('/') ? url.slice(1) : url;
  if(!url.startsWith("http")){
    url = API_BASE_URL + url
  }
  if (isLoading) {
    // wx.showLoading({
    //   title: '请稍候...',
    //   mask: true
    // })
  }
  let info = wx.getAccountInfoSync()
  return new Promise(function (resolve, reject) {
    wx.request({
      url: url,
      data: data,
      method: method,
      header: {
        'Content-Type': contentType,
        'maAppId': info.miniProgram.appId || '',
        'X-EOA-TOKEN': wx.getStorageSync('X-EOA-TOKEN') || ''
      },
      success: function (res) {
        if (res.statusCode === 200) {
          if (res.data.code === 401) {
            wx.removeStorageSync('X-EOA-TOKEN');
            showMsg({
              msg: '请先登录！',
              success: () => {
                wx.reLaunch({
                  url: '/pages/login/login',
                })
              }
            })
            return
          }
          resolve(res.data);
        } else {
          reject(res.data.msg || res.data.message);
        }
      },
      fail: function (err) {
        showMsg('网络不给力，请稍后再试~')
        reject(err)
      },
      complete: function (res) {
        if (res.statusCode === 200) {
          if (res.data.code === 0 || res.data.code === 401) {
            wx.hideLoading()
          } else {

          }
        } else {
          console.info('服务器开小差了，URL：' + url)
          // showMsg({ msg: '服务器开小差了，URL：' + url });
        }
      }
    })
  });
}

/**
 * 增强版消息提示框
 * @param {Object|string} options 配置对象或消息内容
 * @param {string} [options.msg] 提示内容
 * @param {boolean} [options.mask=true] 是否显示透明蒙层
 * @param {number} [options.duration=2000] 提示持续时间
 * @param {string} [options.icon='none'] 图标类型
 * @param {Function} [options.success] 提示结束后的回调函数
 */
function showMsg(options) {
  // 参数标准化处理
  const isLegacyCall = typeof options === 'string';
  const params = {
    msg: '',
    mask: true,
    duration: 2000,
    icon: 'none',
    success: null,
    ...(isLegacyCall ? {
      msg: options,
      mask: arguments[1] !== undefined ? arguments[1] : true,
      duration: arguments[2] !== undefined ? arguments[2] : 2000,
      icon: arguments[3] !== undefined ? arguments[3] : 'none',
      success: arguments[4]
    } : options)
  };

  // 参数校验
  const validIcons = new Set(['success', 'loading', 'none']);
  if (!validIcons.has(params.icon)) {
    console.warn(`Invalid icon type: ${params.icon}, using 'none' instead`);
    params.icon = 'none';
  }

  if (typeof params.duration !== 'number' || params.duration <= 0) {
    params.duration = 2000;
  } else {
    params.duration = Math.min(params.duration, 10000); // 微信限制最大10秒
  }

  // 核心功能
  wx.showToast({
    title: params.msg,
    icon: params.icon,
    mask: !!params.mask,
    duration: params.duration,
    success: () => {
      // 微信没有原生的结束回调，用定时器模拟
      params.success && setTimeout(params.success, params.duration);
    },
    fail: (err) => {
      console.error('showToast failed:', err);
      // 失败时立即执行回调（可选）
      params.success && params.success();
    }
  });
}
// 校验手机号码和座机号
function validatePhoneNumber(phoneNumber) {
  // 手机号码正则
  const mobileRegex = /^1[3-9]\d{9}$/;
  // 座机号正则（带区号）
  const landlineWithAreaCodeRegex = /^\d{3,4}-\d{7,8}$/;
  // 座机号正则（不带区号）
  const landlineWithoutAreaCodeRegex = /^\d{7,8}$/;

  if (mobileRegex.test(phoneNumber)) {
    return true;
    return '手机号码格式正确';
  } else if (landlineWithAreaCodeRegex.test(phoneNumber)) {
    return true;
    return '座机号格式正确（带区号）';
  } else if (landlineWithoutAreaCodeRegex.test(phoneNumber)) {
    return true;
    return '座机号格式正确（不带区号）';
  } else {
    return false;
    return '号码格式错误';
  }
}
// 邮箱格式校验方法
function validateEmail(email) {
  // 邮箱正则表达式（支持大多数常见格式）
  const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
  return emailRegex.test(email);
}
//密码加密
function encode64(input) {
  var keyStr = "ABCDEFGHIJKLMNOP" + "QRSTUVWXYZabcdef" + "ghijklmnopqrstuv" + "wxyz0123456789+/" + "=";
  var output = "";
  var chr1, chr2, chr3 = "";
  var enc1, enc2, enc3, enc4 = "";
  var i = 0;
  do {
    chr1 = input.charCodeAt(i++);
    chr2 = input.charCodeAt(i++);
    chr3 = input.charCodeAt(i++);
    enc1 = chr1 >> 2;
    enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
    enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
    enc4 = chr3 & 63;
    if (isNaN(chr2)) {
      enc3 = enc4 = 64;
    } else if (isNaN(chr3)) {
      enc4 = 64;
    }
    output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2)
      + keyStr.charAt(enc3) + keyStr.charAt(enc4);
    chr1 = chr2 = chr3 = "";
    enc1 = enc2 = enc3 = enc4 = "";
  } while (i < input.length);

  return output;
}
//判断字符串第一个字符如果是'/'就去掉
function removeLeadingSlash(str) {
  return typeof str === 'string' ? str.replace(/^\//, '') : str;
}

module.exports = {
  formatTime,
  generateUUID,
  API_BASE_URL,
  API_BASE_APP_URL,
  request,
  showMsg,
  validatePhoneNumber,
  validateEmail,
  encode64,
  removeLeadingSlash
}
